from django.http import JsonResponse
from django.views import View
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from question.models import Question, Label
from question.serializers.questions import QuestionsIdLabelNewSerializer, QuestionsSerializer, \
    CommentQuestionSerializer, AnswerQuestionSerializer
from question.utils import get_CommentQuestionSerializer, get_AnswerQuestionSerializer, get_user_dict
from users.models import User


class QuestionsIdLabelNewView(ListAPIView):
    """最新回答的问题"""
    serializer_class = QuestionsIdLabelNewSerializer

    def get_queryset(self):

        # 获取参数
        id = self.kwargs.get('id', '-1')
        # 判断请求是否合法
        if not id:
            return
        # 查询全部数据
        if id == '-1':
            question_objs = Question.objects.all()
            # 没有数据
            if question_objs.count() == 0:
                return

            # 有数据
            return question_objs.order_by('-replytime')

        # 返回查询集
        return Question.objects.filter(id=id)

    # 重写方法
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        serializer = self.get_serializer(queryset, many=True)

        # 重构序列化数据
        for data in serializer.data:
            # 空列表
            labels = []

            # 删除元数据
            data_list = data.pop('labels')
            for name in data_list:
                # 重构数据
                labels.append(name.get('label_name'))

            # 添加数据
            data['labels'] = labels

        # 返回
        return Response(serializer.data)


# 热门回答的问题
class QuestionsIdLabelHOTView(ListAPIView):
    serializer_class = QuestionsIdLabelNewSerializer

    def get_queryset(self):

        # 获取参数
        id = self.kwargs.get('id', '-1')
        # 判断请求是否合法
        if not id:
            return
        # 查询全部数据
        if id == '-1':
            question_objs = Question.objects.all()
            # 没有数据
            if question_objs.count() == 0:
                return

            # 有数据
            return question_objs.order_by('-reply')

        # 返回查询集
        return Question.objects.get(id=id)

    # 重写方法
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        serializer = self.get_serializer(queryset, many=True)

        # 重构序列化数据
        for data in serializer.data:
            # 空列表
            labels = []

            # 删除元数据
            data_list = data.pop('labels')
            for name in data_list:
                # 重构数据
                labels.append(name.get('label_name'))

            # 添加数据
            data['labels'] = labels

        # 返回
        return Response(serializer.data)


# 等待回答的问题
class QuestionsIdLabelWaitView(ListAPIView):
    serializer_class = QuestionsIdLabelNewSerializer

    def get_queryset(self):

        # 获取参数
        id = self.kwargs.get('id', '-1')
        # 判断请求是否合法
        if not id:
            return
        # 查询全部数据
        if id == '-1':
            question_objs = Question.objects.filter(reply=0)
            # 没有数据
            if question_objs.count() == 0:
                return

            # 有数据
            return question_objs

        # 返回查询集
        return Question.objects.get(id=id)

    # 重写方法
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        serializer = self.get_serializer(queryset, many=True)

        # 重构序列化数据
        for data in serializer.data:
            # 空列表
            labels = []

            # 删除元数据
            data_list = data.pop('labels')
            for name in data_list:
                # 重构数据
                labels.append(name.get('label_name'))

            # 添加数据
            data['labels'] = labels

        # 返回
        return Response(serializer.data)


# 发布问题/问题详情
class QuestionsModelViewSet(ModelViewSet):
    serializer_class = QuestionsSerializer
    queryset = Question

    # 发布问题
    def create(self, request, *args, **kwargs):
        # 获取用户
        user = request.user

        # 是否登陆
        if not user:
            return Response({'message': "未登陆", 'success': False})

        # 提取标签
        labels = request.data.pop('labels')
        # 设置用户
        request.data['user_id'] = user.id
        # 创建问题
        question = self.get_queryset().objects.create(**request.data)

        # 保存标签
        for item in labels:
            label = Label.objects.get(id=item)
            question.labels.add(label)

        # 返回
        return Response({'message': "ok", 'success': True})

    # 问题详情
    def retrieve(self, request, *args, **kwargs):

        instance = self.get_object()
        serializer = self.get_serializer(instance)

        # 获取序列化器对象数据
        serializer_data_dict = serializer.data

        # 提取数据
        data_list = serializer_data_dict['labels']

        # 修改标签
        for i in range(len(data_list)):
            serializer_data_dict['labels'][i] = data_list[i].get('label_name')

        # 问题评论列表
        serializer_data_dict['comment_question'] = get_CommentQuestionSerializer(serializer_data_dict['id'])
        # 问题回答列表
        serializer_data_dict['answer_question'] = get_AnswerQuestionSerializer(serializer_data_dict['id'])

        instance.visits += 1
        instance.save()

        # 返回
        return Response(serializer_data_dict)


# 问题有用
class QuestionsIdUsefulView(View):
    def put(self, request, id):
        # 获取用户信息
        user_dict = get_user_dict(request)

        # 判断用户是否合法
        if user_dict:
            # 获取用户
            user = User.objects.get(id=user_dict['user_id'])
        else:
            return JsonResponse({'message': '未登录', 'success': False})

        # 验证评价
        try:
            question = Question.objects.get(id=id)

            question.useful_count += 1
            question.save()

        except Exception as e:
            # 查询错误
            return JsonResponse({'message': '查询错误', 'success': False})

        return JsonResponse({'message': 'ok', 'success': True})


# 问题没用
class QuestionsIdUnusefulView(View):
    def put(self, request, id):
        # 获取用户信息
        user_dict = get_user_dict(request)

        # 判断用户是否合法
        if user_dict:
            # 获取用户
            user = User.objects.get(id=user_dict['user_id'])
        else:
            return JsonResponse({'message': '未登录', 'success': False})

        # 验证评价
        try:
            question = Question.objects.get(id=id)
            question.useful_count -= 1

            # 验证最小
            if question.useful_count < 0:
                question.useful_count = 0
                question.save()
                return JsonResponse({'message': '已经最小了, 你和我有仇吗?', 'success': False})

            question.save()

        except Exception as e:

            # 数据库错误
            return JsonResponse({'message': '数据库错误', 'success': False})

        return JsonResponse({'message': 'ok', 'success': True})

